import React, { useCallback, useMemo } from 'react';
import { SearchPageStoreContext } from 'context/searchPageStore';
import { useLocalStore } from 'hooks';
import { observer } from 'mobx-react-lite';
import SearchPageStore from 'store/SearchPageStore';
import OrgReposContainerStore from 'store/SearchPageStore/OrgReposContainerStore';
import SearchContainerStore from 'store/SearchPageStore/SearchContainerStore';

import Text, { TEXT_VIEW } from 'components/Text';
import { classnames } from 'utils';

import PageStepper from './components/PageStepper';
import OrgReposContainer from './containers/OrgReposContainer';
import SearchContainer from './containers/SearchContainer';

import classes from './SearchPage.module.scss';

const cnSearchPage = classnames(classes, 'search-page');

const SearchPage: React.FC = () => {
    const searchPage = useMemo(() => new SearchPageStore(), []);
    const orgReposContainer = useMemo(() => new OrgReposContainerStore(searchPage), [searchPage]);
    const searchContainer = useMemo(() => new SearchContainerStore(searchPage), [searchPage]);

    const { setCurrentPage, currentPage, setResultsElement, pagesCount } = useLocalStore(() => searchPage);
    const { fetchOrganizationRepos } = useLocalStore(() => orgReposContainer);
    const { inputValue, dropdownValues } = useLocalStore(() => searchContainer);

    const onPageChange = useCallback(
        (page: number) => {
            setCurrentPage(page);
            fetchOrganizationRepos({
                organization: inputValue ?? '',
                currentPage: page,
                type: dropdownValues.map(({ key }) => key).join(','),
            });
        },
        [dropdownValues, inputValue],
    );

    return (
        <SearchPageStoreContext.Provider value={{ searchPage, searchContainer, orgReposContainer }}>
            <div className={cnSearchPage()}>
                <div className={cnSearchPage('title')} ref={setResultsElement}>
                    <Text view={TEXT_VIEW.title} className={cnSearchPage('title-mainTitle')}>
                        List organization repositories
                    </Text>
                    <Text view={TEXT_VIEW.p20} className={cnSearchPage('title-secondaryTitle')} color="secondary">
                        Lists repositories for the specified organization
                    </Text>
                </div>
                <SearchContainer />
                <OrgReposContainer />
                {pagesCount && <PageStepper currentPage={currentPage} pagesCount={pagesCount} getPage={onPageChange} />}
            </div>
        </SearchPageStoreContext.Provider>
    );
};

export default observer(SearchPage);
